package com.cxd.sms.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cxd.app.entity.base.SmsInfoBase;
import com.cxd.app.entity.base.UserMessageTemplateBase;
import com.cxd.base.common.exception.SmsSendErrorException;
import com.cxd.base.util.BeanTools;
import com.cxd.message.service.MessageService;
import com.cxd.sms.service.SmsService;

/**
 * 发短信 返回信息详见文档。
 * 
 * @author Administrator
 * 
 */
@Service("smsService")
public class SmsServiceImpl extends SmsService {
	@Resource
	public BeanTools bt;
	
	@Resource
	public MessageService messageService;
	
	private static Properties props = new Properties(); 
	static{
		try {
			props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("zucp_sms_config.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(String content, String mobileNumber) {
		String sn = props.getProperty("sn");
		String pwd = props.getProperty("password");
		if (sn == null || pwd == null) {
			throw new SmsSendErrorException("短信发送失败，sn或password未定义");
		}
		try {
			content = URLEncoder.encode(content, "utf-8");
			ZucpWebServiceClient client = new ZucpWebServiceClient(sn, pwd);
			String result_mt = client.mdSmsSend_u(mobileNumber, content, "","", "");
			if (result_mt.startsWith("-") || result_mt.equals(""))// 发送短信，如果是以负号开头就是发送失败。
			{
				throw new SmsSendErrorException("短信发送失败，错误代码：" + result_mt);
			}
		} catch (UnsupportedEncodingException e) {
			throw new SmsSendErrorException(null, e);
		}
	}

	public void sendSMS(UserMessageTemplateBase umt, Map<String, String> params,
			String mobileNumber) {
		String msg = messageService.replaceParams(umt, params);
		//发送短信
		this.send(msg, mobileNumber);
	}
	
	// 保存发送的短信
	public void saveSmsInfo(SmsInfoBase smsInfo) throws SmsSendErrorException {
		bt.add(smsInfo);
	}
}
